clc;
clear;
close all;

filenames = ["airtrain", "watertrain", "test1", "test2", "test3", "testMdis", "testMdis2", "lub"];

num_subsegment = 10;
fnum_subsegment = 2;
other = 2;
% variation, 

num_type = 4;

for f = 1 : length(filenames)
    load("new_data/" + filenames(f) + ".mat");
    num_sample = size(tag1rssi, 1);
    num_segment = size(tag1rssi, 2);
    
    dataCell = cell(num_type, 1);
    dataCell{1} = tag1rssi;
    dataCell{2} = tag1phase;
    dataCell{3} = tag2rssi;
    dataCell{4} = tag2phase;
    
    features = zeros(num_type, num_sample, num_segment, other + fnum_subsegment * num_subsegment);
    for t = 1 : num_type
        for i = 1 : num_sample
            mu = mean(dataCell{t}(i, 1, 1 : 10));
            for j = 1 : num_segment
                dt = double(permute(dataCell{t}(i, j, :), [3 1 2]));
                dt_len = length(dt);
                
                % variance
            	features(t, i, j, 1) = var(dt);
                
                % mean deviation
                avg = mean(dt);
                features(t, i, j, 2) = (mu - avg)/(mu + 70);
                
                if t <= 2
                    ref = 2;
                else
                    ref = -2;
                end
                
                dt_ref = double(permute(dataCell{t + ref}(i, j, :), [3 1 2]));
                subsegment_len = min(floor(dt_len / num_subsegment), floor(length(dt_ref) / num_subsegment));
                
                subsegments = reshape(dt(1 : subsegment_len * num_subsegment), subsegment_len, num_subsegment)';
                subsegments_ref = reshape(dt_ref(1 : subsegment_len * num_subsegment), subsegment_len, num_subsegment)';

                % subsegment: gap
                for k = 1 : num_subsegment
                    features(t, i, j, other + k) = mean(subsegments(k, :) - subsegments_ref(k, :));
                end
                
                % subsegment: slope
                for k = 1 : num_subsegment
                    y = subsegments(k, :)';
                    x = (1 : subsegment_len)';
                    model = fit(x, y, 'poly1');
                    features(t, i, j, other + num_subsegment + k) = model.p1;
                end
            end
        end 
    end 
    save("new_data/feature-" + filenames(f) + ".mat", "features");
end